package com.rc.saas.mini.controller.rc;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.rc.saas.base.MinipBaseController;
import com.rc.saas.mini.common.base.DataTResponse;
import com.rc.saas.mini.common.mq.MqConfig;
import com.rc.saas.mini.common.mq.MqProducer;
import com.rc.saas.mini.minip.vo.LoginInfoVo;
import com.rc.saas.mini.model.member.MemberInfo;
import com.rc.saas.mini.model.rc.*;
import com.rc.saas.mini.service.rc.RcMsgNotificationService;
import com.rc.saas.mini.service.rc.RcOperatorApplyService;
import com.rc.saas.mini.service.rc.RcOperatorService;
import com.rc.saas.mini.vo.base.RcPageVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.BeanClassLoaderAware;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * @Description
 * @Author
 * @Date: 2022-06-01
 */

@Api(tags = "22.加盟商申请表")
@Controller
@RequestMapping("/rcOperator")
public class RcOperatorController extends MinipBaseController {

    private static Logger logger = LogManager.getLogger(RcOperatorController.class);

    @Autowired
    private RcOperatorService rcOperatorService;
    @Autowired
    private RcOperatorApplyService rcOperatorApplyService;
    @Autowired
    private RcMsgNotificationService rcMsgNotificationService;

    @Autowired
    private MqProducer mqProducer;

    ///**
    // * 增、改
    // */
    //@ApiOperation("提交 加盟商申请")
    //@RequestMapping(value = "/saveRcOperator", method = RequestMethod.POST)
    //@ResponseBody
    //private DataTResponse<String> saveOperator(HttpServletRequest request, RcOperator rcOperator) {
    //    LoginInfoVo loginInfo = readLoginInfo(request);
    //    if (loginInfo == null || loginInfo.getMemberId() == null) {
    //        return DataTResponse.FAIL_LOGIN();
    //    }
    //
    //    RcOperatorApplyExample example = new RcOperatorApplyExample();
    //    example.createCriteria().andMemberIdEqualTo(loginInfo.getMemberId());
    //    example.setOrderByClause("last_updated_time desc,created_time desc");
    //    List<RcOperatorApply> oldList = rcOperatorApplyService.selectByExample(example);
    //    if (oldList != null && oldList.size() > 0
    //            && oldList.stream()
    //            .filter(data -> "0".equals(data.getStatus()) || "1".equals(data.getStatus())).findFirst().orElseGet(() -> null) != null) {
    //        return DataTResponse.FAIL("用户已申请!");
    //    }
    //
    //    RcOperatorApply rcOperatorApply=new RcOperatorApply();
    //    BeanUtils.copyProperties(rcOperator,rcOperatorApply);
    //    //rcOperatorApply.setOperatorId(null);
    //    rcOperatorApply.setOperatorName(rcOperator.getOperatorName());
    //    rcOperatorApply.setContactName(rcOperator.getContactName());
    //    rcOperatorApply.setLoginName(rcOperator.getPhone());
    //    rcOperatorApply.setCompanyCredit(rcOperator.getLicense());
    //    rcOperatorApply.setAddress(rcOperator.getAddress());
    //
    //    rcOperatorApply.setMemberId(loginInfo.getMemberId());
    //    rcOperatorApply.setTenantCode(loginInfo.getTenantCode());
    //    if(rcOperator.getLoginName()==null){
    //        rcOperatorApply.setLoginName(loginInfo.getMobile());
    //    }
    //    if (rcOperatorApply.getCompanyCredit()==null||rcOperatorApply.getCompanyCredit().length() < 8) {
    //        return DataTResponse.FAIL("统一社会信用编码位数过少或者不存在!");
    //    }
    //    rcOperatorApply.setTenantOperatorCode(rcOperator.getLicense().substring(0, 8));
    //    rcOperatorApply.setCreatedTime(new Date());
    //    rcOperatorApply.setCreatedBy(loginInfo.getMemberId() + "");
    //    //rcOperatorService.insertByReturnId(rcOperator);
    //    rcOperatorApplyService.insertByReturnId(rcOperatorApply);
    //    HashMap<String, Long> map = new HashMap<>();
    //    map.put("rcOperatorApplyId", rcOperatorApply.getRcOperatorApplyId());
    //    // 发送mq 给后台
    //    mqProducer.send(MqConfig.platform_apply, JSON.toJSONString(map));
    //
    //    RcMsgNotification rcMsgNotification = new RcMsgNotification();
    //    rcMsgNotification.setTenantCode(loginInfo.getTenantCode());
    //    rcMsgNotification.setMsgType("1");
    //    rcMsgNotification.setMsgId(rcOperatorApply.getRcOperatorApplyId().toString());
    //    rcMsgNotificationService.saveRcMsgNotification(rcMsgNotification);
    //    return DataTResponse.SUCCESS();
    //}

    /**
     * 增、改
     */
    @ApiOperation("提交 加盟商申请")
    @RequestMapping(value = "/saveRcOperator", method = RequestMethod.POST)
    @ResponseBody
    private DataTResponse<String> saveOperator(HttpServletRequest request, RcOperator rcOperator) {
        LoginInfoVo loginInfo = readLoginInfo(request);
        if (loginInfo == null || loginInfo.getMemberId() == null) {
            return DataTResponse.FAIL_LOGIN();
        }

        RcOperatorExample example = new RcOperatorExample();
        example.createCriteria().andMemberIdEqualTo(loginInfo.getMemberId());
        example.setOrderByClause("last_updated_time desc,created_time desc");
        List<RcOperator> oldList = rcOperatorService.selectByExample(example);
        if (oldList != null && oldList.size() > 0
                && oldList.stream()
                .filter(data -> "0".equals(data.getApplyStatus()) || "1".equals(data.getApplyStatus())).findFirst().orElseGet(() -> null) != null) {
            return DataTResponse.FAIL("用户已申请!");
        }
        rcOperator.setOperatorId(null);
        rcOperator.setMemberId(loginInfo.getMemberId());
        rcOperator.setTenantCode(loginInfo.getTenantCode());
        if(rcOperator.getLoginName()==null){
            rcOperator.setLoginName(loginInfo.getMobile());
        }
        if (rcOperator.getLicense()==null||rcOperator.getLicense().length() < 8) {
            return DataTResponse.FAIL("统一社会信用编码位数过少或者不存在!");
        }
        rcOperator.setOperatorType("2");
        rcOperator.setTenantOperatorCode(rcOperator.getLicense().substring(0, 8));
        rcOperator.setCreatedTime(new Date());
        rcOperator.setCreatedBy(loginInfo.getMemberId() + "");
        rcOperatorService.insertByReturnId(rcOperator);
        HashMap<String, Long> map = new HashMap<>();
        map.put("operatorId", rcOperator.getOperatorId());
        // 发送mq 给后台
        mqProducer.send(MqConfig.platform_apply, JSON.toJSONString(map));

        RcMsgNotification rcMsgNotification = new RcMsgNotification();
        rcMsgNotification.setTenantCode(loginInfo.getTenantCode());
        rcMsgNotification.setMsgType("1");
        rcMsgNotification.setMsgId(rcOperator.getOperatorId().toString());
        rcMsgNotificationService.saveRcMsgNotification(rcMsgNotification);
        return DataTResponse.SUCCESS();
    }


    /**
     * 查询
     */
    @ApiOperation("查询单个 加盟商")
    @RequestMapping(value = "/selectByOperatorId", method = RequestMethod.POST)
    @ResponseBody
    @ApiImplicitParams({
            @ApiImplicitParam(name = "operatorId", paramType = "query", value = "加盟商申请id", required = false)})
    private DataTResponse<RcOperator> selectByOperatorId(HttpServletRequest request, Long operatorId) {
        LoginInfoVo loginInfoVo = readLoginInfo(request);
        if (loginInfoVo == null || loginInfoVo.getMemberId() == null) {
            return DataTResponse.FAIL_LOGIN();
        }
        RcOperator Operator = rcOperatorService.selectByPrimaryKey(operatorId);
        if (!loginInfoVo.getMemberId().equals(Operator.getMemberId())) {
            Operator = null;
        }
        return DataTResponse.SUCCESS_DATA(Operator);
    }

    /**
     * 查询列表分页
     */
    @ApiOperation("查询列表分页 加盟商申请表")
    @RequestMapping(value = "/listPageByOperator", method = RequestMethod.POST)
    @ResponseBody
    private DataTResponse<PageInfo<RcOperator>> listPageByOperator(HttpServletRequest request, RcPageVo rcPageVo) {
        //Page
        LoginInfoVo loginInfoVo = readLoginInfo(request);
        if (loginInfoVo == null || loginInfoVo.getMemberId() == null) {
            return DataTResponse.FAIL_LOGIN();
        }
        RcOperator Operator = new RcOperator();
        Operator.setMemberId(loginInfoVo.getMemberId());
        PageHelper.startPage(rcPageVo.getPageNo(), rcPageVo.getPageSize());
        List<RcOperator> list = rcOperatorService.listByCondition(Operator);
        PageInfo<RcOperator> pageInfo = new PageInfo<>(list);
        return DataTResponse.SUCCESS_DATA(pageInfo);
    }
}
